package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ForwardDetailsActivity;
import com.srwl.mytx.activity.WithdrawDetailActivity;
import com.srwl.mytx.constant.StatementConstant;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.AdvertisementDetailActivity;
import com.srwl.mytx.activity.AdvertisementOrderDetailActivity;
import com.srwl.mytx.activity.CoinTransferDetailActivity;
import com.srwl.mytx.activity.DonationDetailActivity;
import com.srwl.mytx.activity.MultipleCouponDetailActivity;
import com.srwl.mytx.activity.RechargeDetailActivity;
import com.srwl.mytx.activity.SingleCouponDetailActivity;
import com.srwl.mytx.activity.TaskDetailActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CoinTransfer;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.Statement;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.service.StatementService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.math.BigDecimal;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 余额收支清单适配器
 */
public class BalanceStatementAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "BalanceStatementAdapter";
    private List<Statement> statementList;

    private boolean bol_noData;//标记是否有数据
    private boolean bol_requestError;//标记是否请求出错
    private Context mContext;


    public BalanceStatementAdapter(Context context, List<Statement> couponList) {
        mContext = context;
        this.statementList = couponList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            return new NoDataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.no__data__layout, parent, false));
        } else if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return new RequestErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.request_error_layout, parent, false));
        }
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.statement_item, parent, false);

        return new ItemViewHolder(view);
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        int viewType = getItemViewType(position);
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            NoDataViewHolder noDataViewHolder = (NoDataViewHolder) holder;
            noDataViewHolder.tv_tips.setText("没有记录");
        } else if (viewType == Constant.ITEM_TYPE_NORMAL) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            setItemViews(itemViewHolder, position);
        }
    }


    private void setItemViews(ItemViewHolder itemViewHolder, int position) {
        Statement statement = statementList.get(position);
        BigDecimal amount = statement.getAmount();
        if (amount.compareTo(BigDecimal.ZERO) > 0) {
            itemViewHolder.tvMoneyAmount.setTextColor(mContext.getResources().getColor(R.color.rp_money_red_light));
            itemViewHolder.tvMoneyAmount.setText("+" + Utils.moneyFormat(amount));
        } else {
            itemViewHolder.tvMoneyAmount.setTextColor(mContext.getResources().getColor(R.color.text_black));
            itemViewHolder.tvMoneyAmount.setText(Utils.moneyFormat(amount));
        }
        itemViewHolder.tvDate.setText(DateUtils.getTimestampString(statement.getCreated()));
        itemViewHolder.itemView.setOnLongClickListener(v -> {
            ConfirmDialog dialog = new ConfirmDialog(mContext, "提醒", "确定删除本条记录吗？", true);
            dialog.setConfirmListener(() -> deleteStatement(statement.getId(), position));
            dialog.show();
            return true;
        });

        switch (statement.getType()) {

            case StatementConstant.STATEMENT_TYPE_RECHARGE://充值
                itemViewHolder.tv_title.setText("充值");
                itemViewHolder.tv_type.setText("[充值]");//标题和分类看起来重复了，没有必要再设置 类型，但是不设置类型的话，类型所在的位置看起来很空，不好看
                GlideLoadUtils.glideLoad(mContext, R.drawable.tx_recharge_2, itemViewHolder.ivAvatar);
                itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RechargeDetailActivity.startActivity(mContext, statement.getTargetId());
                    }
                });
                break;

            case StatementConstant.STATEMENT_TYPE_TRANSFER://提现
                itemViewHolder.tv_title.setText("提现");
                itemViewHolder.tv_type.setText("[提现]");
                GlideLoadUtils.glideLoad(mContext, R.drawable.tx_withdraw_2, itemViewHolder.ivAvatar);
                itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WithdrawDetailActivity.startActivity(mContext, statement.getTargetId());
                    }
                });
                break;

            case StatementConstant.STATEMENT_TYPE_DONATION:
                handleDonationStatement(itemViewHolder, statement);
                break;
            case StatementConstant.STATEMENT_TYPE_COUPON:
                handleCouponStatement(itemViewHolder, statement);
                break;

            case StatementConstant.STATEMENT_TYPE_COIN_TRANSFER: {
                itemViewHolder.tv_title.setText(statement.getTitle());
                showIcon(itemViewHolder, statement);
                itemViewHolder.tv_type.setText("[转账]");
                itemViewHolder.itemView.setOnClickListener(v -> {

                    //根据流水生成一条 金币转账信息
                    CoinTransfer transfer = new CoinTransfer();
                    transfer.setId(statement.getId());
                    transfer.setCreated(statement.getCreated());
                    double doubleAmount = amount.doubleValue();
                    transfer.setAmount(Math.abs(doubleAmount));
                    //流水清单中，金额是正数，说明是金额增加，是金币转账中的接收方，
                    if (doubleAmount > 0) {
                        transfer.settId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                    }
                    CoinTransferDetailActivity.startActivity(mContext, transfer);
                });
            }
            break;

            case StatementConstant.STATEMENT_TYPE_REWARD_TASK: {
                itemViewHolder.tv_title.setText(statement.getTitle());
                showIcon(itemViewHolder, statement);
                itemViewHolder.tv_type.setText("[悬赏结算]");
                itemViewHolder.itemView.setOnClickListener(v -> TaskDetailActivity.startActivity(mContext, statement.getTargetId()));
            }
            break;
            case StatementConstant.STATEMENT_TYPE_ADVERTISEMENT_ORDER: {
                itemViewHolder.tv_title.setText(statement.getTitle());
                showIcon(itemViewHolder, statement);
                itemViewHolder.tv_type.setText("[广告位订单]");
                itemViewHolder.itemView.setOnClickListener(v -> AdvertisementOrderDetailActivity.startActivity(mContext, statement.getTargetId()));
            }
            break;

            case StatementConstant.STATEMENT_TYPE_LIVE: {
                handleLiveStatement(itemViewHolder, statement);
            }
            break;
            case StatementConstant.STATEMENT_TYPE_ADVERTISEMENT_DEPOSIT:
                handleAdvertisementDepositStatement(itemViewHolder, statement);
                break;
            case StatementConstant.STATEMENT_TYPE_REWARD_DEPOSIT:
                handleRewardDepositStatement(itemViewHolder, statement);
                break;

        }


    }

    private void handleDonationStatement(ItemViewHolder itemViewHolder, Statement statement) {
        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);

        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleDonationStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {
            case StatementConstant.STATEMENT_SUBTYPE_SEND_DONATION_TO_SCHOOL:
                itemViewHolder.tv_type.setText("[捐赠到学校]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SEND_DONATION_TO_INDUSTRY:
                itemViewHolder.tv_type.setText("[捐赠到行业]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SEND_DONATION_TO_AREA:
                itemViewHolder.tv_type.setText("[捐赠到地区]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SEND_DONATION_TO_EXPOSE:
                itemViewHolder.tv_type.setText("[捐赠到曝光]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SEND_DONATION_TO_REWARD:
                itemViewHolder.tv_type.setText("[捐赠到悬赏]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SEND_DONATION_TO_PERSON:
                itemViewHolder.tv_type.setText("[捐赠给个人]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_RECEIVE_DONATION_PERSON:
                itemViewHolder.tv_type.setText("[收到个人捐赠]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_RECEIVE_DONATION_TOPIC:
                itemViewHolder.tv_type.setText("[收到焦点转发捐赠]");
                itemViewHolder.itemView.setOnClickListener(v -> ForwardDetailsActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REVOKE_DONATION_ACTIVE:
                itemViewHolder.tv_type.setText("[主动拆回捐赠]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REVOKE_DONATION_PASSIVE:
                itemViewHolder.tv_type.setText("[悬赏取消 捐赠自动返还]");
                itemViewHolder.itemView.setOnClickListener(v -> DonationDetailActivity.startActivity(mContext, statement.getTargetId()));
                break;
            default:
                Log.e(TAG, "handleDonationStatement: 还有分类没有处理" + JSONObject.toJSONString(statement));

        }

    }

    private void handleCouponStatement(ItemViewHolder itemViewHolder, Statement statement) {
        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);

        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleCouponStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {

            case StatementConstant.STATEMENT_SUBTYPE_SEND_SINGLE_COUPON:
                itemViewHolder.tv_type.setText("[发红包]");
                itemViewHolder.itemView.setOnClickListener(v -> SingleCouponDetailActivity.startActivity(mContext, statement.getTargetId(), true));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SEND_MULTIPLE_COUPON:
                itemViewHolder.tv_type.setText("[发红包]");
                itemViewHolder.itemView.setOnClickListener(v -> getMultipleCouponInfo(statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_SINGLE_COUPON_EXPIRED:
                itemViewHolder.tv_type.setText("[红包过期自动拆回]");
                itemViewHolder.itemView.setOnClickListener(v -> SingleCouponDetailActivity.startActivity(mContext, statement.getTargetId(), true));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_MULTIPLE_COUPON_EXPIRED:
                itemViewHolder.tv_type.setText("[红包过期自动拆回]");
                itemViewHolder.itemView.setOnClickListener(v -> getMultipleCouponInfo(statement.getTargetId()));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_RECEIVE_SINGLE_COUPON:
                itemViewHolder.tv_type.setText("[收红包]");
                itemViewHolder.itemView.setOnClickListener(v -> SingleCouponDetailActivity.startActivity(mContext, statement.getTargetId(), false));
                break;
            case StatementConstant.STATEMENT_SUBTYPE_RECEIVE_MULTIPLE_COUPON:
                itemViewHolder.tv_type.setText("[收红包]");
                itemViewHolder.itemView.setOnClickListener(v -> getMultipleCouponInfo(statement.getTargetId()));
                break;
            default:
                Log.e(TAG, "handleCouponStatement: 还有分类没有处理" + JSONObject.toJSONString(statement));

        }
    }

    private void handleAdvertisementDepositStatement(ItemViewHolder itemViewHolder, Statement statement) {

        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);
        itemViewHolder.itemView.setOnClickListener(v -> AdvertisementDetailActivity.startActivity(mContext, statement.getTargetId()));
        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleRewardDepositStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_DEPOSIT_PUT:
                itemViewHolder.tv_type.setText("[广告位投放]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_DEPOSIT_INCREASE:
                itemViewHolder.tv_type.setText("[广告位保证金追加]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_DEPOSIT_REVOKE:
                itemViewHolder.tv_type.setText("[广告位保证金撤回]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_OFFER_SUCCESS_DEPOSIT_REDUCE:
                itemViewHolder.tv_type.setText("[广告位竞价成功，保证金自动返还]");
                break;
        }

    }

    private void handleRewardDepositStatement(ItemViewHolder itemViewHolder, Statement statement) {
        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);
        itemViewHolder.itemView.setOnClickListener(v -> TopicDetailsActivity.startActivity(mContext, statement.getTargetId()));
        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleRewardDepositStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_PUBLISH:
                itemViewHolder.tv_type.setText("[发布悬赏]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_AMOUNT_INCREASE:
                itemViewHolder.tv_type.setText("[悬赏金增加]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_AMOUNT_REDUCE:
                itemViewHolder.tv_type.setText("[悬赏金减少]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_CANCEL:
                itemViewHolder.tv_type.setText("[悬赏取消]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_COMPLETE:
                itemViewHolder.tv_type.setText("[悬赏完成]");
                break;
            default:
                Log.e(TAG, "handleRewardDepositStatement: 有类型没有处理，，，，，" + JSONObject.toJSONString(statement));
        }
    }

    private void handleLiveStatement(ItemViewHolder itemViewHolder, Statement statement) {
        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);

        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleLiveStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {

            case StatementConstant.STATEMENT_SUBTYPE_LIVE_REWARD:
            case StatementConstant.STATEMENT_SUBTYPE_LIVE_MULCT:
                itemViewHolder.tv_type.setText("[直播消费]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_LIVE_PROFIT:
                itemViewHolder.tv_type.setText("[直播收益]");
                break;
        }
    }

    private void showIcon(ItemViewHolder itemViewHolder, Statement statement) {
        String iconUrl = Utils.getIconUrl(statement);
        if (GlideLoadUtils.isActivityAlive((Activity) mContext)) {
            Glide.with(mContext).load(iconUrl).transform(new CircleCrop()).into(itemViewHolder.ivAvatar);
        }
    }

    private void deleteStatement(String id, int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) mContext).showToast_v1(mContext.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(StatementService.class)
                .deleteStatement(id)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "删除出错：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "删除出错：" + result.getMsg());
                            return;
                        }
                        statementList.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, statementList.size() - position);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });

    }

    private void getMultipleCouponInfo(String couponId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) mContext).showToast_v1(mContext.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .getCouponAndSenderInfo(couponId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取红包详情出错：" + response.message());

                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取红包详情出错：" + result.getMsg());

                            return;
                        }
                        Object data = result.getData();
                        if (data != null) {
                            JSONObject object = (JSONObject) data;
                            Log.d(TAG, "获取优惠卷详情完成" + object.toString());
                            Coupon couponInfo = object.toJavaObject(Coupon.class);
                            MultipleCouponDetailActivity.startActivity(mContext, couponInfo);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    @Override
    public int getItemCount() {
        if (bol_noData || bol_requestError) {
            return 1;
        }
        return statementList.size();
    }


    @Override
    public int getItemViewType(int position) {
        if (bol_noData) {
            return Constant.ITEM_TYPE_NO_DATA;
        } else if (bol_requestError) {
            return Constant.ITEM_TYPE_REQUEST_ERROR;
        }
        return Constant.ITEM_TYPE_NORMAL;
    }


    /**
     * 显示普通视图
     * 有数据的时候调用
     */
    public void showNormalView() {
        bol_noData = false;
        bol_requestError = false;
        notifyDataSetChanged();
    }

    /**
     * 显示无数据视图
     */
    public void showNoDataView() {
        bol_noData = true;
        notifyDataSetChanged();
    }

    /**
     * 显示请求数据错误视图
     */
    public void showErrorView() {
        bol_requestError = true;
        notifyDataSetChanged();
    }

    private static class ItemViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tv_title;
        TextView tvDate;
        TextView tvMoneyAmount;
        TextView tv_type;

        ItemViewHolder(View v) {
            super(v);
            initView(v);
        }

        private void initView(View v) {
            ivAvatar = v.findViewById(R.id.iv_item_avatar_icon);
            tv_title = v.findViewById(R.id.tv_title);
            tvDate = v.findViewById(R.id.tv_time);
            tvMoneyAmount = v.findViewById(R.id.tv_item_money_amount);
            tv_type = v.findViewById(R.id.tv_type);
        }
    }


}
